import { basePopupMixins } from './index.js'
import VForm from '../VForm/index.vue'
import { isFunction } from 'lodash-es'

export function formPopupMixin(config = {}) {
  return {
    mixins: [
      basePopupMixins({
        ...config,
        getDialogListeners() {
          const listenets = config.getDialogListeners ? config.getDialogListeners.call(this) : {}
          const closed = listenets.closed
          listenets.closed = () => {
            closed && closed()
            this.$refs.VForm.reset()
          }
          return listenets
        },
        footer() {
          return {
            ...(config.footer ? config.footer.call(this) : {}),
            clickConfirmButton: this.formPopupMixin__handleConfirm
          }
        },
        render(h) {
          const options = isFunction(config.formOptions) ? config.formOptions.call(this) : config.formOptions
          return options
            ? h(VForm, {
              props: { options },
              ref: 'VForm'
            })
            : ''
        }
      })
    ],
    methods: {
      async formPopupMixin__handleConfirm({ showLoading, cancelLoading, close }) {
        this.$refs.VForm.validate()
          .then(async(params) => {
            try {
              showLoading()
              await config.onSubmit.call(this, params)
              close()
            } finally {
              cancelLoading()
            }
          })
      }
    }
  }
}
